package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.SerialNoHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.SaasSpecialParamPojo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.PayPlanSheetDao;
import com.xbongbong.saas.domain.entity.PayPlanSheetEntity;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PayPlanSheetSubDataModel;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/25 15:28
 * @since v1.0
 */
@Service("payPlanSheetModel")
public class PayPlanSheetModelImpl implements PayPlanSheetModel {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PayPlanSheetDao payPlanSheetDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private PayPlanSheetSubDataModel payPlanSheetSubDataModel;
    @Resource
    private SerialNoHelp serialNoHelp;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;

    @Override
    public Integer insert(PayPlanSheetEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        payPlanSheetDao.insert(entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        return null;
    }

    @Override
    public List<PayPlanSheetEntityExt> insertBatch(List<PayPlanSheetEntityExt> list) throws XbbException{
        // TODO: 2020/9/22
        return insertBatch(list, null);
    }

    /**
     * 根据data里某个条件搜索
     *
     * @param attr   data里属性
     * @param value  data里属性的值
     * @param param 参数
     */
    @Override
    public Integer getCountByOneCondition(String attr, Object value, Map<String, Object> param) {
        attr = "$." + attr;
        return payPlanSheetDao.getCountByOneCondition(attr, value, param);
    }

    @Override
    public List<PayPlanSheetEntityExt> insertBatch(List<PayPlanSheetEntityExt> list, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException{
        for (PayPlanSheetEntityExt entity : list) {
            paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(list);
        payPlanSheetDao.insertBatch(list);
        //ES数据插入
        List<InsertDTO> insertList = new ArrayList<>();
        for (PayPlanSheetEntityExt item : list) {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setWaitUntil(WriteRequest.RefreshPolicy.NONE);
            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
            item.setDataId(item.getId());
            PayPlanSheetEntity paasFormDataEntity = new PayPlanSheetEntity();
            BeanUtil.copyProperties(item, paasFormDataEntity);
            insertDTO.setSource(BeanUtil.convertBean2Map(paasFormDataEntity, true));
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
            insertList.add(insertDTO);
        }
        if(refreshPolicy == null){
            paasEsModel.insertBatch(insertList);
        }else{
            paasEsModel.insertBatch(insertList, refreshPolicy);
        }

        paasFormSubDataModel.insertBatchSubFormData(list, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        return list;
    }

    @Override
    public Integer update(PayPlanSheetEntityExt entity) throws XbbException {

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer integer = payPlanSheetDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        if (Objects.equals(1, integer) || Objects.equals(1, updateSub)) {
            long now = DateUtil.getInt()+1;
            integer = payPlanSheetDao.updateTime(now, entity.getId(), entity.getCorpid());
            InsertDTO insertDTO = paasEsModel.getSaveDTO(entity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }

        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = payPlanSheetDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        }
        // todo
        if (!subList.isEmpty()) {
            payPlanSheetSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = payPlanSheetDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET, refreshPolicy);
        }
        // todo
        if (!subList.isEmpty()) {
            payPlanSheetSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, boolean needThrow) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = payPlanSheetDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET, needThrow);
        }
        // todo
        if (!subList.isEmpty()) {
            payPlanSheetSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateFlowStatusBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            integer = payPlanSheetDao.updateFlowStatusBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        }
        // todo
        if (!subList.isEmpty()) {
            payPlanSheetSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List<PayPlanSheetEntityExt> findEntitys(Map<String, Object> param) {
        List<PayPlanSheetEntityExt> entitys = payPlanSheetDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return payPlanSheetDao.getEntitysCount(param);
    }

    @Override
    public Integer save(PayPlanSheetEntityExt payPlanSheetEntityExt) throws XbbException {
        if (payPlanSheetEntityExt.getId() == null || payPlanSheetEntityExt.getId() == 0L) {
            return insert(payPlanSheetEntityExt);
        }  else {
            return update(payPlanSheetEntityExt);
        }
    }

    @Override
    public PayPlanSheetEntityExt getByKey(Long key, String corpid) {
        PayPlanSheetEntityExt entityExt = payPlanSheetDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        return entityExt;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        paasEsModel.delete(deleteDTO);
        Integer integer = payPlanSheetDao.deleteByKey(key, corpid);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        return integer;
    }

    @Override
    public Integer deleteBatch(List<Long> list, String corpid, Integer del) throws XbbException {
        Integer integer = payPlanSheetDao.deleteBatch(list, corpid);
        //ES根据id批量设置del=1
        paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteBatch(List<Long> list, String corpid, Integer del, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = payPlanSheetDao.deleteBatch(list, corpid);
        //ES根据id批量设置del=1
        if(refreshPolicy == null){
            paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        }else{
            paasEsModel.deleteBatch(list, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET, refreshPolicy);
        }
        paasFormSubDataModel.deleteBatchByDataId(list, corpid, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }
    
    /**
     * @param list   更新的数据
     * @param corpid 公司id
     * @return
     * @author chenshan
     * @date 2019/11/28 21:27
     */
    @Override
    public Integer updateBatchForData(List<? extends PaasFormDataEntity> list, String corpid) throws XbbException {
        // TODO: 2020/9/22
        return updateBatchForData(list, corpid, true);
    }
    
    public Integer updateBatchForData(List<? extends PaasFormDataEntity> list, String corpid, boolean needThrow) throws XbbException {
        if( CollectionsUtil.isEmpty(list)){
            return 0;
        }
        for (PaasFormDataEntity paasFormDataEntityExt : list) {
            paasFormSubDataModel.transferSubForm(paasFormDataEntityExt, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        }
        StandardizeDataUtil.standardize4EntityList(list);
        Integer updateCount = payPlanSheetDao.updateBatchForAll(list,corpid);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : list) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET));
        }
//        for ( PayPlanSheetEntityExt entityExt : list){
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setEsId(corpid+"_"+entityExt.getId());
//            PayPlanSheetEntityExt payPlanSheetEntityExt = new PayPlanSheetEntityExt();
//            BeanUtil.copyProperties(entityExt, payPlanSheetEntityExt);
//            payPlanSheetEntityExt.setDataId(entityExt.getId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(payPlanSheetEntityExt));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
//            insertDTOList.add(insertDTO);
//        }
        paasEsModel.updateBatch(insertDTOList,WriteRequest.RefreshPolicy.WAIT_UNTIL,needThrow);
        // todo
        return updateCount;
    }

    @Override
    public List<PayPlanSheetEntityExt> getPaySheetByCorpidScript(Map<String, Object> param) {
        List<PayPlanSheetEntityExt> entityExts = payPlanSheetDao.getPaySheetByCorpidScript(param);
        return entityExts;
    }

    @Override
    public List<String> getCorpidList() {
        return payPlanSheetDao.getCorpidList();
    }

    @Override
    public List<PayPlanSheetEntityExt> findAffectBalanceEntitys(Map<String, Object> param) {
        //只要父 和  类型只要2，3，6
        param.put(BasicConstant.ALONE_IN, Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.PARENT.getCode()));
        return payPlanSheetDao.findAffectBalanceEntitys(param);
    }

    @Override
    public List<PayPlanSheetEntityExt> getPaySheetByIdIn(String corpid,List<Long> payPlanSheetIdIn){
        List<PayPlanSheetEntityExt> entityExts = payPlanSheetDao.getPaySheetByIdIn(corpid, payPlanSheetIdIn);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        return entityExts;
    }

    @Override
    public Long getMaxId(Map<String, Object> param) {
        return payPlanSheetDao.getMaxId(param);
    }
    @Override
   public List<PayPlanSheetEntityExt> getParentAndSubPaySheet(String corpid,List<String> uuidIn){
        List<PayPlanSheetEntityExt> entityExts = payPlanSheetDao.getParentAndSubPaySheet(corpid, uuidIn);
        paasFormSubDataModel.findSubEntity(corpid, entityExts, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET_SUB);
        return entityExts;
    }

    @Override
    public List<PayPlanSheetEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return payPlanSheetDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        //一期退货退款那边关了新建红冲回款单需要把编号带过去，二期采购退货关联红冲付款单编号应该是类似的逻辑
        //红冲付款单时 编号处理
        SaasSpecialParamPojo saasSpecialParamPojo = formatExplainDTO.getSaasSpecialParamPojo();
        if (saasSpecialParamPojo != null && Objects.equals(saasSpecialParamPojo.getFromRed(), BasicConstant.ONE)) {
            List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
            String serialNo = "";
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                serialNo = serialNoHelp.getSerialNo(serialNo, formatExplainDTO.getCorpid(), formatExplainDTO.getFormId(), fieldAttrEntity);
            }
            PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
            Long id = dataEntity.getId();
            String sheetNo = dataEntity.getSerialNo();
            dataEntity.setSerialNo(serialNo);
            dataEntity.getData().put(PaySheetEnum.ORIGIN_ID.getAttr(), defaultAttrHelp.packegeLinkBusinessJsonArray(id, sheetNo));
        }
    }

    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4ShowBySource(result, PaySheetEnum.LINK_SUPPLIER.getAttr(), PaySheetEnum.SUPPLIER_LINK_TEXT.getAttr(), PaySheetEnum.LINK_SUPPLIER.getFieldType(), XbbRefTypeEnum.SUPPLIER.getCode(), XbbRefTypeEnum.PURCHASE.getCode(), formDataUpdateGetDTO.getCorpid());
        showFormatHelp.formatLinkBusiness4Show(result, PaySheetEnum.LINK_PURCHASE.getAttr(), PaySheetEnum.PURCHASE_LINK_TEXT.getAttr(), PaySheetEnum.LINK_PURCHASE.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PaySheetEnum.PAY_PLAN.getAttr(), PaySheetEnum.PAY_PLAN_LINK_TEXT.getAttr(), PaySheetEnum.PAY_PLAN.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, PaySheetEnum.ORIGIN_ID.getAttr(), PaySheetEnum.ORIGIN_ID_LINK_TEXT.getAttr(), PaySheetEnum.ORIGIN_ID.getFieldType());
    }

    /**
     * 更新付款单时间
     *
     * @param id
     * @param corpid
     */
    @Override
    public void updateTime(Long id, String corpid) throws XbbException {
        Long updateTime = DateTimeUtil.getInt();
        payPlanSheetDao.updateTime(updateTime,id, corpid);
        InsertDTO insertDTO = new InsertDTO();
        insertDTO.setEsId(corpid+"_"+id);
        Map<String, Object> map = new HashMap<>();
        map.put(FieldTypeEnum.UPDATETIME.getAlias(), updateTime);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET);
        paasEsModel.update(insertDTO);
    }
}
